package com.gitee.qdbp.general.common.web.controller.editor;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.base.annotation.OperateRecord;
import com.gitee.qdbp.base.enums.OperateType;
import com.gitee.qdbp.base.utils.WebFileHandler;
import com.gitee.qdbp.general.common.api.files.service.IWebFileService;

/**
 * CKEditor文件上传下载控制器
 *
 * @author zhaohuihua
 * @version 150325
 */
@Controller
@RequestMapping("actions/common/ckeditor")
public class CkeditorController {

    @Autowired
    private IWebFileService webFileService;

    private WebFileHandler uploader;

    @PostConstruct
    protected void init() {
        this.uploader = new WebFileHandler(webFileService);
    }

    /**
     * 上传图片
     * 
     * @param file
     * @return
     */
    @RequestMapping(value = "upload-jsonp", method = RequestMethod.POST)
    @OperateRecord(value = "文件上传", type = OperateType.UPDATE)
    public void uploadByJsonp(@RequestParam("upload") MultipartFile file, String CKEditorFuncNum, String folder,
            String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, Object> extra = findExtraParams(request);
        
        String callback = "window.parent.CKEDITOR.tools.callFunction";
        PrintWriter out = response.getWriter();
        try {
            filename = file.getOriginalFilename(); // 获取上传文件的名称
            String url = uploader.upload(file, folder, filename, extra);
            out.print("<script type='text/javascript'>");
            out.print(callback);
            out.print("(" + CKEditorFuncNum + ",'" + url + "','')");
            out.print("</script>");
        } catch (ServiceException e) {
            out.print("<script type='text/javascript'>");
            out.print(callback);
            out.print("(" + CKEditorFuncNum + ",''," + "'" + e.getMessage() + "');");
            out.print("</script>");
        }
    }

    /**
     * 上传粘贴图片
     * 
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "upload-file", method = RequestMethod.POST)
    @OperateRecord(value = "文件上传", type = OperateType.UPDATE)
    public Map<String, Object> uploadFile(@RequestParam("upload") MultipartFile file, String CKEditorFuncNum,
            String folder, String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, Object> extra = findExtraParams(request);

        JSONObject json = new JSONObject();
        try {
            filename = file.getOriginalFilename(); // 获取上传文件的名称
            String url = uploader.upload(file, folder, filename, extra);

            json.put("uploaded", 1);
            json.put("fileName", file.getOriginalFilename());
            json.put("url", url);
        } catch (ServiceException e) {
            JSONObject error = new JSONObject();
            error.put("message", e.toString());
            json.put("error", error);
        }

        return json;
    }

    private Map<String, Object> findExtraParams(HttpServletRequest request) {

        // 用JSON格式GET请求提交参数SpringMvc报400错误: extra={'module':'uc','content-type':'portrait'}
        // 改为标准格式提交参数extra-module=uc&extra-content-type=portrait
        String prefix = "extra-";
        Map<String, Object> extra = new HashMap<>();
        Enumeration<String> keys = request.getParameterNames();
        while (keys.hasMoreElements()) {
            String k = keys.nextElement();
            if (k.startsWith(prefix)) {
                extra.put(k.substring(prefix.length()), request.getParameter(k));
            }
        }
        return extra;
    }
}
